<template>
  <main>
    <div class="main">
      <div class="section-content">
        <div class="search-input-wrapper">
          <a-input-search
            placeholder="请输入关键字"
            :allowClear="true"
            v-model="searchKeywords"
            @focus="inputSearchOnFocus"
            @change="inputSearchChange"
            @blur="inputSearchOnBlur"
            @pressEnter="searchPressEnter"
          />
        </div>
        <div v-if="keywords && Array.isArray(keywords) && keywords.length > 0" class="search-container">
          <h4 class="search-headline">#热搜</h4>
          <span v-if="keywords">
            <a-tag class="tag" v-for="(item, index) in keywords" :key="index" @click="keywordClick(item)">
              {{ item.keyword }}
            </a-tag>
          </span>
        </div>

        <div>
          <menu-bar-pc :selectedIndex.sync="selectedIndex" :items="categories" :itemClick="menuItemClick"></menu-bar-pc>
        </div>

        <div class="collection-forums">
          <div class="cell" v-for="(item, index) in items" :key="index" @click="itemClick(item)">
            <div class="container">
              <div class="text">
                <div>
                  <div class="headline-container">
                    <h4>{{ item.name }}</h4>
                  </div>
                  <p>{{ item.createTime }}</p>
                </div>
                <div class="content">
                  <div v-html="item.description"></div>
                </div>
              </div>
            </div>
            <div class="actions-container">
              <div @click.stop="commentClick(item)">{{ item.commentCount }}条评论</div>
            </div>
          </div>
        </div>

        <a-pagination
          background
          layout="prev, pager, next"
          :current="currentPage"
          :page-size="pageSize"
          :total="pageTotal"
          @change="paginationOnChange"
        >
        </a-pagination>
      </div>
      <div class="ask-question-actions-panel">
        <a-button class="ask-question-button" type="primary" @click="askQuestionClick()">我要提问</a-button>
      </div>
      <comment-modal ref="commentModal" @ok="commentModalOk"> </comment-modal>
      <ask-question-modal ref="askQuestionModal" @ok="askQuestionModalOk"> </ask-question-modal>
    </div>
  </main>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import CommentModal from './components/CommentModal.vue'
import AskQuestionModal from './components/AskQuestionModal.vue'

export default {
  name: 'List',
  data() {
    return {
      selectedIndex: 0,
      searchKeywords: '',
      model: {
        auditStatus: 0,
      },
      confirmLoading: false,
    }
  },
  components: {
    CommentModal,
    AskQuestionModal,
  },

  computed: {
    ...mapState('forums', {
      categories: (state) => state.categories,
      keywords: (state) => state.keywords,
    }),

    ...mapState('forumsQuestion', {
      items: (state) => state.items,
      pageSize: (state) => state.pageSize,
      pageTotal: (state) => state.pageTotal,
      currentPage: (state) => state.currentPage,
      originalPage: (state) => state.originalPage,
    }),
  },

  created() {
    document.title = '问答区'
    this.updateList()
  },

  activated() {
    this.updateList()
  },

  methods: {
    ...mapActions('forumsQuestion', [
      'getQuestionListAction',
      'submitQuestionAction',
      'updateCurrentPageAction',
      'updateOriginalPageAction',
    ]),

    commentModalOk() {
      console.log('\n\n commentModalOk:' + JSON.stringify('') + '\n\n')
      this.updateList()
    },
    askQuestionModalOk() {
      this.updateList()
    },

    askQuestionClick() {
      console.log('\n\n' + 'ask question click' + '\n\n')
      const that = this
      if (this.isSignedIn) {
        this.$refs.askQuestionModal.add()
      } else {
        this.$router.push({
          path: '/account/sign-in',
        })
      }
    },

    itemClick(item) {
      this.$router.push({
        path: '/forums/qa/detail',
        query: { id: item.id },
      })
    },
    menuItemClick(item, index) {
      this.selectedIndex = index
      this.updateCurrentPageAction(1)
      this.updateList()
    },

    keywordClick(item) {
      this.searchKeywords = item.keyword
      this.updateList()
    },

    /**
     * @description: 输入框编辑聚焦(开始编辑)
     * @param {*}
     * @return {*}
     */
    inputSearchOnFocus() {
      if (!this.searchKeywords) {
        this.updateOriginalPageAction(this.currentPage)
      }
      this.updateCurrentPageAction(1)
      this.isSearchInputing = true
    },

    /**
     * @description: 输入文本变化监听，可以用于Autocomplete的实现
     * @param {*}
     * @return {*}
     */
    inputSearchChange() {
      if (this.isSearchInputing == false) {
        if (!this.searchKeywords) {
          console.log('\n\n this.originalPage = ' + JSON.stringify(this.originalPage) + '\n\n')
          this.updateCurrentPageAction(this.originalPage)
          this.updateList()
        }
      }
    },

    /**
     * @description:输入框失去编辑聚焦
     * @param {*}
     * @return {*}
     */
    inputSearchOnBlur() {
      console.log('\n\n inputSearchOnBlur this.originalPage = ' + JSON.stringify(this.originalPage) + '\n\n')
      this.isSearchInputing = false
      this.updateList()
    },

    /**
     * @description: 键盘enter事件监听
     * @param {*}
     * @return {*}
     */
    searchPressEnter() {
      this.updateList()
    },

    paginationOnChange(value) {
      this.updateCurrentPageAction(value)
      this.updateList()
    },

    updateList() {
      const that = this
      const item = this.categories[this.selectedIndex]
      var categoryId = null
      if (item) {
        categoryId = item.id
      }
      const parameters = {
        pageSize: this.pageSize,
        pageNo: this.currentPage,
        categoryId: categoryId,
        name: this.searchKeywords,
      }
      const isRefresh = true
      const isPC = true
      this.getQuestionListAction({ isRefresh, parameters, isPC }).catch((error) => {
        that.$message.error(error.message)
      })
    },

    commentClick(item) {
      this.$refs.commentModal.show(item.id)
    },

    submitClick() {
      const that = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          that
            .submitQuestionAction(that.model)
            .then((response) => {
              if (response.success) {
                that.model = {}
                that.updateList()
                console.log('\n\n' + '提交成功' + '\n\n')
                that.$message.success('提交成功')
              } else {
                that.$message.error(response.message)
              }
            })
            .catch((error) => {
              that.$message.error(error.message)
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
  },
}
</script>

<style scoped lang="less">
.search-input-wrapper {
  padding-top: 0;
  padding-bottom: 0;
  padding: var(--padding-xxx-small) 0;
}

.search-headline {
  padding: 10px 0;
  white-space: nowrap;
}

.search-container {
  display: flex;
  flex-direction: row;
  width: 50% !important;
  margin: 10px auto;
  padding: 10px 0px;
  align-items: flex-start;
}

.search-container .tag {
  margin: var(--margin-xxx-small) var(--margin-xxx-small);
}
.section-content {
  padding-top: var(--padding-x-small) !important;
  padding-bottom: var(--padding-medium) !important;
}

.activity-selected {
  color: var(--r-primary-color);
  font-weight: 500;
}

.content {
  margin: 10px 10px;
  max-height: 110px;
  overflow: hidden;
  line-height: 1.5em;
  font-size: 14px;
}

.ask-question-container {
  margin: 20px 0px;
  padding: 20px 20px;
  height: 44px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background: white;
  border-radius: 10px;
}

.ask-question-container h3 {
  text-align: left;
}

.ask-question-button-container {
  display: flex;
  justify-content: center;
}
.ask-question-actions-panel {
  position: fixed;
  top: ~'calc(50vh - 0.5 * 160px)';
  right: 0;
  width: 120px;
  height: 160px;
  /* background: white; */
  background: clear;
  /* border: 1px solid rgba(0, 0, 0, 0.1); */
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.ask-question-button {
  margin: 20px 10px;
}

.collection-forums .cell .container .text .headline-container {
  padding: var(--padding-x-small) 0px;
}
.collection-forums .cell .container .content {
  margin: 0 0;
}
</style>
